package com.algebra.util.encrypt;

import com.algebra.util.SymmetricEncryptionUtil;
import com.algebra.util.annotation.FieldEncrypt;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;

/**
 * @author al
 * @date 2022/5/24 16:39
 * @description 处理字段加解密工具类
 */
public class FieldCrypt {

    public static void decryptField(EncryptorProperties props, MetaObject metaObject, FieldSetProperty fieldSetProperty) {
        String fieldName = fieldSetProperty.getFieldName();
        Object objectValue = metaObject.getValue(fieldName);
        if (null != objectValue) {
            if (objectValue instanceof String) {
                try {
                    FieldEncrypt fieldEncrypt = fieldSetProperty.getFieldEncrypt();
                    if (null != fieldEncrypt) {
                        objectValue = SymmetricEncryptionUtil.decrypt(props.getPassword(), (String) objectValue);
                    }
                } catch (Exception var9) {
                    System.err.println("field decrypt: " + var9.getMessage());
                }
            }
            metaObject.setValue(fieldName, objectValue);
        }

    }

    public static boolean encryptField(Configuration var0, EncryptorProperties props, Object var3) throws Exception {
        return DataFilter.insertOrUpdate(var0, var3, (var2x, var3x) -> {
            FieldEncrypt var4 = var3x.getFieldEncrypt();
            if (null != var4) {
                Object var5 = var2x.getValue(var3x.getFieldName());
                if (null != var5) {
                    try {
                        String var6 = SymmetricEncryptionUtil.encrypt(props.getPassword(), (String) var5);
                        var2x.setValue(var3x.getFieldName(), var6);
                    } catch (Exception var7) {
                        System.err.println("field encrypt: " + var7.getMessage());
                    }
                }
            }

        });
    }

}
